Categories
JavaScript Tips

Useful JavaScript Tips — Various Tricks

Spread the love

As with any kind of app, JavaScript apps have to be written well otherwise we will run into all kinds of issues later on. In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Empty a JavaScript Array

To empty a JavaScript array, we can set its length property to 0.

For instance. we can write:

const arr = ['a', 'b', 'c'];
arr.length = 0;

Then arr would be an array with no length.

Likewise, we can just assign it an empty array:

const arr = ['a', 'b', 'c'];
arr.length = [];

Hide DOM Elements Dynamically

DOM elements can be done dynamically using JavaScript.

We can use the stykle.display property to do it.

For instance, we can write:

element.style.display = 'none';

It’s the same as setting display: 'none' .

If we want to toggle them element back on, we can write:

element.style.display = 'block'

Get the Index of Iteration in the for-of Loop

We can get the index of iteration of the for-of loop with the entries method of the array.

Then we can combine that with a destructuring assignment.

For instance, we can write:

for (const [i, v] of ['foo', 'bar', 'baz'].entries()) {
  console.log(i, v);
}

i is the index and v is the value.

Generate a Random Number Between 2 Numbers

We can generate a random number between 2 numbers with some arithmetic and the Math.random method.

For example, we can write:

Math.floor(Math.random() * 10 + 1)

Then we generate numbers between 1 and 10.

Math.floor rounds the generated number down to the nearest integer.

Using map with async Functions

The array instance map method can be used with the Promise.all to return a promise with an array of items mapped to a promise.

For instance, we can write:

const getData = async () => {
  return Promise.all(arr.map(item => asyncFunc(item)))
}

Assuming that asyncFunc is a function that returns a promise, we return an array of promises with the map call.

Therefore, we can use Promise.all on it so that we can invoke them in parallel.

Initialize an Array with Values

We can use the Array constructor with the fill method to create an array and fill it with items.

For instance, we can write:

Array(20).fill(10)

to create an array with 20 empty slots, then fill the slots with 10.

Get the Current URL

The window.location object has various properties about the current URL.

Since window is the global object, we can omit it and just use location .

location.href has the whole URL.

location.hostname has the hostname.

location.origin has the originating URL.

location.hash has the part after the # sign.

location.pathname has the path after the hostname.

location.port has the port number.

location.protocol has the protocol.

location.search has the query string.

Create a Multiline String

A multiline string can be created easily with template literals.

For instance, we can write:

const multilineStr = `hello
world`

Then the string will stay in 2 lines.

Check if a String Starts with a Given String

JavaScript strings have the startsWith method to check if a string starts with a given string.

We can call it by using:

'jane, joe and alex'.startsWith('jane')

Then it would return true .

It also takes a second argument, which lets us specify the index of which character we want to start checking.

For instance, we can write:

'jane, joe and alex'.startsWith('jane', 8)

Then startsWith starts searching at index 8, so it returns false .

Get Unique Values of an Object Property in Array Entries

We can get the unique values of an object in array entries by mapping the values to an array.

Then we use the Set constructor, and then use the spread operator to convert that back to an array.

For example, we can write:

const bills = [{
    date: '2020-01-20',
    amount: '70',
    category: 'phone'
  },
  {
    date: '2020-01-20',
    amount: '20',
    category: 'gas'
  },
  {
    date: '2020-02-20',
    amount: '75',
    category: 'phone'
  }
]

Then we can write:

const categories = [...new Set(bills.map(bill => bill.category))]

Then categories would be [“phone”, “gas”] .

Conclusion

We can get the current URL with the location global object. To empty an array, we can set the length property to 0. Promise.all can be used to run multiple promises in parallel.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *